package com.letu.uid.baidu.worker;

import com.letu.uid.baidu.model.WorkerNodeOfUid;
import com.letu.uid.baidu.util.NetUtils;
import com.letu.uid.baidu.utils.DockerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * DB编号分配器(利用数据库来管理)
 * @author yutianbao
 */
@Component
public class DisposableWorkerIdAssigner implements WorkerIdAssigner {
    private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class);

//    @Autowired
//    ProjectCoreServiceFeign projectCoreServiceFeign;

    /**
     * Assign worker id base on database.<p>
     * If there is host name & port in the environment, we considered that the node runs in Docker container<br>
     * Otherwise, the node runs on an actual machine.
     * 
     * @return assigned worker id
     */
    @Override
    public long assignWorkerId() {
        // build worker node entity
//        WorkerNode workerNodeEntity = buildWorkerNode();
//
//        // add worker node for new (ignore the same IP + PORT)
////        workerNodeService.save(workerNodeEntity);
//        R<WorkerNode> workerNodeR = projectCoreServiceFeign.createBaiduWorkNode(workerNodeEntity);
//        LOGGER.info("Add worker node:" + JSONObject.toJSONString(workerNodeR));
//        return workerNodeR.getData().getId();

        return 0L;
    }

    /**
     * Build worker node entity by IP and PORT
     */
    private WorkerNodeOfUid buildWorkerNode() {
        WorkerNodeOfUid workerNodeEntity = new WorkerNodeOfUid();
        if (DockerUtils.isDocker()) {
            workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
            workerNodeEntity.setHostName(DockerUtils.getDockerHost());
            workerNodeEntity.setPort(DockerUtils.getDockerPort());

        } else {
            workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
            workerNodeEntity.setHostName(NetUtils.getLocalInetAddress().getHostAddress());
            workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RANDOM.nextInt(100000));
        }
        workerNodeEntity.setLaunchDate(LocalDate.now());
        workerNodeEntity.setModified(LocalDateTime.now());
        workerNodeEntity.setCreated(LocalDateTime.now());
        return workerNodeEntity;
    }
    
    private static final Random RANDOM = new Random();
}
